package com.xiaohudie.SGGJUC;

/**
 * @Author xiao hu die
 * @Date 2022/3/6 22:50
 * @Version 1.0
 */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**线程间的精准唤醒
 * 使用定制化通信工具*/
public class TestAnswer {
    public static void main(String[] args) {
     //  testFinally();
        BigCar bigCar = new BigCar();
        new Thread(()-> {
            try {
                bigCar.SoutA();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"AA").start();
        new Thread(()-> {
            try {
                bigCar.SoutB();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"BB").start();
        new Thread(()-> {
            try {
                bigCar.SoutC();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"CC").start();
    }
   public static String testFinally(){
     try {
         System.out.println("正常代码");
         return "啊啊啊";
   }finally {
         System.out.println("finally代码");
     }
    }
}
class BigCar{
    private Lock lock =new ReentrantLock();
    private Integer number =3;
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
   public void SoutA() throws InterruptedException {
       lock.lock();
       try {
           while (number==1) {
               System.out.println(Thread.currentThread().getName() + "--->");
               number =2;
               condition2.signal();
           }
           condition1.await();
       }finally {
           lock.unlock();
       }
   }
    public void SoutB() throws InterruptedException {
        lock.lock();
        try {
            while (number==2) {
                System.out.println(Thread.currentThread().getName() + "--->");
                number =3;
                condition3.signal();
            }
            condition2.await();
        }finally {
            lock.unlock();
        }
    }
    public void SoutC() throws InterruptedException {
        lock.lock();
        try {
            while (number==3) {
                System.out.println(Thread.currentThread().getName() + "--->");
                number=1;
                condition1.signal();
            }
            condition3.await();
        }finally {
            lock.unlock();
        }
    }
}
